import { useEffect, useState } from 'react';
import axios from 'axios';

const useUserPermissions = () => {
    const [permissions, setPermissions] = useState([]);
    const [roles, setRoles] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        console.log('调用useUserPermissions');

        const fetchPermissions = async () => {
            try {
                const response = await axios.get('http://localhost:8080/api/users/getUserPermissions');
                console.log('getUserPermissions response', response);

                // 检查 success 字段以确认请求是否成功
                if (response.data.success) {
                    setPermissions([...response.data.data.permissions]);
                    setRoles([...response.data.data.roles]);
                    setLoading(false);
                    console.log('获取用户权限信息成功！');
                    console.log('后端返回的权限列表：', response.data.data.permissions);
                    console.log('前端存入的权限列表：', permissions);
                } else {
                    // 如果请求不成功，使用返回的消息提示错误
                    console.error(`获取用户权限信息失败：${response.data.message}`);
                    setError(response.data.message);
                    setLoading(false);
                }
            } catch (err) {
                console.error('Failed to fetch user permissions:', err);
                setError('获取用户权限信息失败，请稍后再试！');
                setLoading(false);
            }
        };

        // 从 localStorage 中获取 currentUser 并解析为对象
        const currentUser = localStorage.getItem('currentUser');
        let token = null;

        if (currentUser) {
            try {
                const userObject = JSON.parse(currentUser);
                token = userObject.token;
            } catch (error) {
                console.error('Failed to parse currentUser from localStorage:', error);
            }
        }

        if (token) {
            axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
            fetchPermissions();
        } else {
            setLoading(false);
        }
    }, []);
    // 添加一个新的 useEffect 来监听权限的变化
    useEffect(() => {
    }, [permissions]);


    return { permissions, roles, loading, error };
};

export default useUserPermissions;